package com.hzwq.demo.Email.service;

import com.hzwq.demo.Email.bo.SdteInBox;
import com.hzwq.demo.Email.repository.SdteInBoxRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SdteInBoxServiceImpl implements SdteInBoxService{
    @Autowired
    private SdteInBoxRepository sdteInBoxRepository;

    /**
     * 根据userId查询邮件列表
     */
    public List<SdteInBox> findListEmailByReceiveId(String userId){
        return sdteInBoxRepository.findListEmalByReceiveId(userId);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    public Page<SdteInBox> findPageEmail(SdteInBox entity, Integer page, Integer size) {
        PageRequest pageable = PageRequest.of(page -1, size, Sort.Direction.DESC, "inboxDate");
        Specification<SdteInBox> spec = new Specification<SdteInBox>() {        //查询条件构造
            @Override
            public Predicate toPredicate(Root<SdteInBox> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> par = new ArrayList<Predicate>();
                if(entity.getInboxReceiver() != null && !entity.getInboxReceiver().equals("")){
                    Predicate p1 =cb.equal(root.get("inboxReceiver").as(String.class),  entity.getInboxReceiver() );
                    par.add(p1);

                }
                Predicate[] p = new Predicate[par.size()];
                return   cb.and(par.toArray(p));
            }

        };
        Page<SdteInBox> list= sdteInBoxRepository.findAll(spec,pageable);
        return list;
    }
}
